package com.example;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.database.StudentMessage;
import com.example.entity.Student;
import com.example.view.Customize;
import com.example.view.CustomizeBottom;

import java.util.List;

public class StudentActivity extends AppCompatActivity {
    private Customize customize ;
    private CustomizeBottom customizeBottom ;
    private ListView listView ;
    private ArrayAdapter<Student> adapter ;
    private StudentMessage studentMessage ;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.array);
        listView = findViewById(R.id.listView);
        customize = findViewById(R.id.student_top);
        customizeBottom = findViewById(R.id.student_bottom);

        final EditText editText1 = new EditText(this);
        editText1.setHint("输入在此处");

         studentMessage = new StudentMessage(this) ;

        //获取登录页面传递的登录信息
        SharedPreferences sharedPreferences = getSharedPreferences("loginIdAndName" , Context.MODE_PRIVATE);
        String studentId = sharedPreferences.getString("studentId", "");
        String student_id = sharedPreferences.getString("studentId","");
        boolean isGL = studentMessage.isStudentEnrolled(studentId);

        if (isGL){
            List<Student> students = studentMessage.getAllStudent() ;
            adapter = new ArrayAdapter<com.example.entity.Student>(this ,
                    R.layout.student , R.id.student_name,students){
                @Override
                public View getView(int position , View converView , ViewGroup parent){
                    View view = super.getView(position , converView , parent);
                    TextView textName = view.findViewById(R.id.student_id);
                    TextView textId = view.findViewById(R.id.student_name);
                    SharedPreferences sharedPreferences = getSharedPreferences("loginIdAndName" , Context.MODE_PRIVATE);
                    String loginStudentId = sharedPreferences.getString("studentId", "");
                    Student student =  getItem(position);
                    if (student != null) {
                        if (loginStudentId.equals(String.valueOf(student.getStudentId()))){
                            view.setVisibility(View.GONE);
                        }else {
                            textName.setText(String.valueOf(student.getStudentName()));
                            textId.setText(String.valueOf(student.getStudentId()));
                        }

                    }

                    return view ;
                }
            };

        }else {
            List<Student> students = studentMessage.getStudentsInSameClass(studentId) ;
            adapter = new ArrayAdapter<com.example.entity.Student>(this ,
                    R.layout.student , R.id.student_name,students){
                @Override
                public View getView(int position , View converView , ViewGroup parent){
                    View view = super.getView(position , converView , parent);
                    TextView textName = view.findViewById(R.id.student_id);
                    TextView textId = view.findViewById(R.id.student_name);
                    SharedPreferences sharedPreferences = getSharedPreferences("loginIdAndName" , Context.MODE_PRIVATE);
                    String loginStudentId = sharedPreferences.getString("studentId", "");
                    Student student =  getItem(position);
                    if (student != null) {
                        if (loginStudentId.equals(String.valueOf(student.getStudentId()))){
                            view.setVisibility(View.GONE);
                        }else {
                            textName.setText(String.valueOf(student.getStudentName()));
                            textId.setText(String.valueOf(student.getStudentId()));
                        }

                    }

                    return view ;
                }
            };

        }


         if(isGL){
             //为列表设置点击事件
             listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                 @Override
                 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                     TextView getId = view.findViewById(R.id.student_id);
                     String studentId = getId.getText().toString() ;
//                     boolean is_gl = studentMessage.isStudentEnrolled(studentId);
                     if (studentId.equals(student_id)){
                         new AlertDialog.Builder(StudentActivity.this)
                                 .setMessage("请选择您的操作")
                                 .setPositiveButton("查看信息", new DialogInterface.OnClickListener() {
                                     @Override
                                     public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(StudentActivity.this , StudentInformationActivity.class) ;
                                         intent.putExtra("studentId" , studentId);
                                         Log.d("TAG", "onItemClick: "+studentId);
                                         startActivity(intent);
                                     }
                                 })
                                 .show();
                     }else {
                         new AlertDialog.Builder(StudentActivity.this)
                                 .setMessage("请选择您的操作")
                                 .setPositiveButton("查看信息", new DialogInterface.OnClickListener() {
                                     @Override
                                     public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(StudentActivity.this , StudentInformationActivity.class) ;
                                         intent.putExtra("studentId" , studentId);
                                         Log.d("TAG", "onItemClick: "+studentId);
                                         startActivity(intent);
                                     }
                                 })
                                 .setNeutralButton("删除同学", new DialogInterface.OnClickListener() {
                                     @Override
                                     public void onClick(DialogInterface dialog, int which) {
                                         new AlertDialog.Builder(StudentActivity.this)
                                                 .setMessage("确定删除该同学吗？")
                                                 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                     @Override
                                                     public void onClick(DialogInterface dialog, int which) {
                                                     boolean is_gl = studentMessage.isStudentEnrolled(studentId);
                                                         if (is_gl) {
                                                             AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                                                             builder.setMessage("您所删除的是管理员，请输入该管理员的密码");
                                                             final EditText editText1 = new EditText(StudentActivity.this);
                                                             builder.setView(editText1);
                                                             builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                 @Override
                                                                 public void onClick(DialogInterface dialog, int which) {
                                                                     try {
                                                                         String inputText = editText1.getText().toString().trim();
                                                                         Student student = studentMessage.getStudentById(studentId);
                                                                         if (student != null) {
                                                                             String password = student.getPassword();
                                                                             if (inputText.equals(password)) {
                                                                                 studentMessage.deleteStudent(studentId);
                                                                                 new AlertDialog.Builder(StudentActivity.this)
                                                                                         .setMessage("管理员删除成功")
                                                                                         .setNegativeButton("确定", null)
                                                                                         .create()
                                                                                         .show();
                                                                             } else {
                                                                                 new AlertDialog.Builder(StudentActivity.this)
                                                                                         .setMessage("密码输入错误")
                                                                                         .setNegativeButton("确定", null)
                                                                                         .create()
                                                                                         .show();
                                                                             }
                                                                         } else {
                                                                             // Handle the case where the student is not found
                                                                             new AlertDialog.Builder(StudentActivity.this)
                                                                                     .setMessage("未找到该管理员账户")
                                                                                     .setNegativeButton("确定", null)
                                                                                     .create()
                                                                                     .show();
                                                                         }
                                                                         // Refresh the list after the operation
                                                                         List<Student> updatedStudents = studentMessage.getAllStudent();
                                                                         adapter.clear();
                                                                         adapter.addAll(updatedStudents);
                                                                         adapter.notifyDataSetChanged();
                                                                     } catch (Exception e) {
                                                                         // Log and handle the exception
                                                                         Log.e("StudentActivity", "Error deleting student", e);
                                                                         new AlertDialog.Builder(StudentActivity.this)
                                                                                 .setMessage("发生错误：" + e.getMessage())
                                                                                 .setNegativeButton("确定", null)
                                                                                 .create()
                                                                                 .show();
                                                                     }
                                                                 }
                                                             });
                                                             builder.setNegativeButton("取消", null);
                                                             builder.create().show();
                                                         }else {
                                                         studentMessage.deleteStudent(studentId);
                                                         new AlertDialog.Builder(StudentActivity.this)
                                                                 .setMessage("成员删除成功")
                                                                 .setNegativeButton("确定" ,null)
                                                                 .create()
                                                                 .show();
                                                     }
                                                         // 删除操作成功后，刷新学生列表
                                                         List<Student> updatedStudents = studentMessage.getAllStudent();
                                                         adapter.clear();
                                                         adapter.addAll(updatedStudents);
                                                         adapter.notifyDataSetChanged();
                                                     }
                                                 })
                                                 .setNegativeButton("取消", null) // 点击取消，对话框消失，不执行任何操作
                                                 .show();
                                     }
                                 })
                                 .show();
                     }

                 }
             });
         }else {
             listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                 @Override
                 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                     TextView getId = view.findViewById(R.id.student_id);
                     String studentId = getId.getText().toString() ;
                     Intent intent = new Intent(StudentActivity.this , StudentInformationActivity.class) ;
                     intent.putExtra("studentId" , studentId);
                     Log.d("TAG", "onItemClick: "+studentId);
                     startActivity(intent);
                 }
             });
         }



        listView.setAdapter(adapter);
        customize.setLeftBtnNoVisible(true);//不显示
        customize.setRightBtnNoVisible(true);
        customize.setTitleText("同学");
        customizeBottom.setStudentBtnBackground(R.color.bottomUse);
        customizeBottom.setCourseBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StudentActivity.this, CurriculumActivity.class);
                startActivity(intent);
                finish();
            }
        });
        customizeBottom.setPersonBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StudentActivity.this, PersonalActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

}
